<template>
  <div class="registrations-container">
    <h1 class="page-title">我的报名记录</h1>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.title"
        placeholder="活动标题搜索"
        clearable
        @clear="handleReset"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select 
        v-model="searchForm.status" 
        placeholder="报名状态" 
        clearable
        @clear="handleReset"
        class="status-select"
      >
        <el-option label="待审核" :value="0" />
        <el-option label="已通过" :value="1" />
        <el-option label="已拒绝" :value="2" />
        <el-option label="已取消" :value="3" />
      </el-select>
      
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    
    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待审核" name="pending"></el-tab-pane>
      <el-tab-pane label="已通过" name="approved"></el-tab-pane>
      <el-tab-pane label="已拒绝" name="rejected"></el-tab-pane>
      <el-tab-pane label="已取消" name="canceled"></el-tab-pane>
    </el-tabs>
    
    <!-- 报名列表 -->
    <div class="registration-list" v-if="registrationList.length > 0">
      <el-card 
        v-for="(item, index) in registrationList" 
        :key="index" 
        class="registration-card"
        :class="{ 
          'pending': item.status === 0, 
          'approved': item.status === 1, 
          'rejected': item.status === 2,
          'canceled': item.status === 3
        }"
      >
        <div class="card-header">
          <h2 class="activity-title">{{ item.activityTitle }}</h2>
          <div class="registration-status">
            <el-tag v-if="item.status === 0" type="info">待审核</el-tag>
            <el-tag v-else-if="item.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="item.status === 2" type="danger">已拒绝</el-tag>
            <el-tag v-else-if="item.status === 3" type="info">已取消</el-tag>
          </div>
        </div>
        
        <div class="registration-info">
          <p><strong>报名时间：</strong>{{ formatDate(item.createTime) }}</p>
          <p><strong>活动时间：</strong>{{ formatDate(item.activityStartTime) }} - {{ formatDate(item.activityEndTime) }}</p>
          <p><strong>活动地点：</strong>{{ item.activityLocation }}</p>
          <p v-if="item.status === 2"><strong>拒绝原因：</strong>{{ item.rejectReason || '无' }}</p>
          <p v-if="item.status === 1"><strong>签到状态：</strong>
            <el-tag :type="item.checkInTime ? 'success' : 'warning'" size="small">
              {{ item.checkInTime ? '已签到' : '未签到' }}
            </el-tag>
          </p>
        </div>
        
        <div class="registration-actions">
          <el-button 
            v-if="item.status === 0 || item.status === 1" 
            type="danger" 
            size="small" 
            @click="handleCancel(item.id)"
          >
            取消报名
          </el-button>
          
          <el-button 
            v-if="item.status === 1 && !item.checkInTime && canCheckIn(item)" 
            type="success" 
            size="small" 
            @click="handleCheckIn(item.id)"
          >
            签到
          </el-button>
          
          <el-button 
            type="primary" 
            size="small" 
            @click="goToActivityDetail(item.activityId)"
          >
            查看活动
          </el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 空状态 -->
    <el-empty 
      v-else 
      description="暂无报名记录" 
      :image-size="200"
    ></el-empty>
    
    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserRegistrations, cancelRegistration, checkInRegistration } from '@/api/registration'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

const router = useRouter()

// 状态映射
const statusMap = {
  'all': null,
  'pending': 0,
  'approved': 1,
  'rejected': 2,
  'canceled': 3
}

// 响应式变量
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const registrationList = ref([])
const searchForm = reactive({
  title: '',
  status: null
})

// 获取报名数据
const fetchRegistrations = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      title: searchForm.title || undefined
    }
    
    // 根据标签或搜索状态设置status
    if (activeTab.value !== 'all') {
      params.status = statusMap[activeTab.value]
    } else if (searchForm.status !== null) {
      params.status = searchForm.status
    }
    
    const res = await getUserRegistrations(params)
    registrationList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取报名记录失败:', error)
    ElMessage.error('获取报名记录失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRegistrations()
}

// 重置
const handleReset = () => {
  searchForm.title = ''
  searchForm.status = null
  currentPage.value = 1
  fetchRegistrations()
}

// 切换标签
const handleTabClick = () => {
  searchForm.status = statusMap[activeTab.value]
  currentPage.value = 1
  fetchRegistrations()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRegistrations()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRegistrations()
}

// 取消报名
const handleCancel = (id) => {
  ElMessageBox.confirm('确定要取消该报名吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await cancelRegistration(id)
      ElMessage.success('取消报名成功')
      fetchRegistrations()
    } catch (error) {
      console.error('取消报名失败:', error)
      ElMessage.error('取消报名失败')
    }
  }).catch(() => {})
}

// 签到
const handleCheckIn = async (id) => {
  try {
    await checkInRegistration(id)
    ElMessage.success('签到成功')
    fetchRegistrations()
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  }
}

// 跳转到活动详情
const goToActivityDetail = (activityId) => {
  router.push({
    name: 'ActivityDetail',
    params: { id: activityId }
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未设置'
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 判断是否可以签到（活动开始后才能签到）
const canCheckIn = (item) => {
  if (!item.activityStartTime) return false
  const now = dayjs()
  const startTime = dayjs(item.activityStartTime)
  const endTime = dayjs(item.activityEndTime)
  return now.isAfter(startTime) && now.isBefore(endTime)
}

// 页面加载时获取数据
onMounted(() => {
  fetchRegistrations()
})
</script>

<style scoped>
.registrations-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  min-width: 220px;
}

.status-select {
  min-width: 120px;
}

.registration-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.registration-card {
  transition: all 0.3s;
  border-left: 4px solid #e6e6e6;
}

.registration-card.pending {
  border-left-color: #909399;
}

.registration-card.approved {
  border-left-color: #67c23a;
}

.registration-card.rejected {
  border-left-color: #f56c6c;
}

.registration-card.canceled {
  border-left-color: #909399;
}

.registration-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.activity-title {
  font-size: 18px;
  margin: 0;
  color: #303133;
  flex: 1;
  word-break: break-word;
}

.registration-info {
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.registration-info p {
  margin: 8px 0;
}

.registration-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .registration-list {
    grid-template-columns: 1fr;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .search-input, .status-select {
    width: 100%;
  }
}
</style> 